package com.shiloop.flashlight;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageButton;
import android.widget.Scroller;

/**
 * Created by skiloop on 2014/9/12.
 */
public class LockImageButton extends ImageButton {
    private static final String TAG = "LockImageButton";
    private OnLockChangeListener onLockChangeListener;
    private Scroller mScroller;
    private boolean mIsLocked;
    private float mLastMotionY;
    private float mStartY;
    private float mLockScrollLimit = 5;

    public LockImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        mScroller = new Scroller(context);
        mIsLocked = false;
    }

    public boolean isLocked() {
        return mIsLocked;
    }

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        final float y = event.getY();
//        switch (event.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                mLastMotionY = y;
//                mStartY = y;
//                break;
//            case MotionEvent.ACTION_MOVE:
//                int delta = (int) (mLastMotionY - y);
//                mLastMotionY = y;
//                Log.d(TAG, "delta: " + delta);
//                scrollBy(0, delta);
//                break;
//            case MotionEvent.ACTION_UP:
//                if (mLastMotionY - mStartY > mLockScrollLimit) {
//                    changeLockState();
//                }
//                snapBack();
//                break;
//        }
//        return true;
//    }

    private void snapBack() {
        mScroller.startScroll(0, getScrollY(), 0, -getScrollY(), Math.abs(getScrollY()) / 4);
    }

    private void changeLockState() {
        setLock(!mIsLocked);
    }

    private void updateViewStatus() {
        // TODO update button status according to lock state
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();
        }
    }

    public void setOnLockChangeListener(OnLockChangeListener listener) {
        if (null != listener) {
            onLockChangeListener = listener;
        }
    }

    public interface OnLockChangeListener {
        public void onLockChange();
    }

    public void setLock(boolean lock) {
        mIsLocked = lock;
        updateViewStatus();
        if (null != onLockChangeListener) {
            onLockChangeListener.onLockChange();
        }
    }
}
